package com.twb.quartz.util;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import com.twb.core.util.BeanUtils;
import com.twb.core.util.DateUtil;
import com.twb.core.util.ExceptionUtil;
import com.twb.quartz.constants.QuartzConstants;
import com.twb.quartz.entity.twbQuartzJob.TwbQuartzJob;

/**
 * @ClassName AbstractQuartzJob
 * @Description 抽象quartz调用
 * @author DSY
 * @date 2021年12月26日 上午11:35:47
 */
public abstract class AbstractQuartzJob implements Job {
	private static final Logger log = LoggerFactory.getLogger(AbstractQuartzJob.class);

	@Value("${twb.log.enabled}")
	private Boolean logEnable = true;
	
	/**
	 * 线程本地变量
	 */
	private static ThreadLocal<Date> threadLocal = new ThreadLocal<>();

	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		TwbQuartzJob job = new TwbQuartzJob();
		BeanUtils.copyProperties(context.getMergedJobDataMap().get(QuartzConstants.TASK_PROPERTIES), job);
		try {
			before(context, job);
			if (job != null) {
				doExecute(context, job);
			}
			after(context, job, null);
		} catch (Exception e) {
			log.error("任务执行异常  - ：", e);
			after(context, job, e);
		}
	}

	/**
	 * 执行前
	 *
	 * @param context 工作执行上下文对象
	 * @param sysJob  系统计划任务
	 */
	protected void before(JobExecutionContext context, TwbQuartzJob job) {
		threadLocal.set(new Date());
	}

	/**
	 * 执行后
	 *
	 * @param context 工作执行上下文对象
	 * @param sysJob  系统计划任务
	 */
	protected void after(JobExecutionContext context, TwbQuartzJob job, Exception e) {
		Date startTime = threadLocal.get();
		threadLocal.remove();

		// 记录运行日志
		if(logEnable) {
			Date stopTime = new Date();
			log.debug(job.getName() + "," + job.getGroupName() + "," + job.getInvokeTarget() + ",startTime:"
					+ DateUtil.format(startTime) + "stopTime:" + DateUtil.format(stopTime));
			long runMs = stopTime.getTime() - startTime.getTime();
			log.debug(job.getName() + " 总共耗时：" + runMs + "毫秒");
		}
		
		if (e != null) {
			String errorMsg = StringUtils.substring(ExceptionUtil.getExceptionMessage(e), 0, 2000);
			log.error(job.getName() + " 执行异常：" + errorMsg);
		}

	}

	/**
	 * 执行方法，由子类重载
	 *
	 * @param context 工作执行上下文对象
	 * @param sysJob  系统计划任务
	 * @throws Exception 执行过程中的异常
	 */
	protected abstract void doExecute(JobExecutionContext context, TwbQuartzJob job) throws Exception;
}
